package utils

import (
	"crypto/md5"
	"encoding/hex"
	"sort"
	"strings"
)

func Sign(m map[string]string, keys string) string {
	signList := make([]string, 0, len(m))
	for k := range m {
		signList = append(signList, k)
	}
	sort.Strings(signList)
	list := make([]string, 0, len(m))
	for _, v := range signList {
		list = append(list, v+"="+m[v])
	}
	tmp := strings.Join(list, "&")
	return Md5(tmp + keys)
}

func Md5(text string) string {
	ctx := md5.New()
	ctx.Write([]byte(text))
	return hex.EncodeToString(ctx.Sum(nil))
}

func ParamsJoin(m map[string]string) string {
	signList := make([]string, 0, len(m))
	for k := range m {
		signList = append(signList, k)
	}
	sort.Strings(signList)
	list := make([]string, 0, len(m))
	for _, v := range signList {
		list = append(list, v+"="+m[v])
	}
	return strings.Join(list, "&")
}
